package com.heima.wemedia.service.impl;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dto.WmMaterialDto;
import com.heima.model.wemedia.pojo.WmMaterial;
import com.heima.model.wemedia.pojo.WmNewsMaterial;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author TheCai
 * @date 2021/5/27 15:54
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial>
    implements WmMaterialService {
  @Autowired FileStorageService fileStorageService;

  @Value("${file.oss.prefix}")
  String prefix;

  @Value("${file.oss.endpoint}")
  String endpoint;

  @Value("${file.oss.web-site}")
  String webSite;

  /**
   * 上传图片
   * @param multipartFile
   * @return
   */
  @Override
  public ResponseResult uploadPicture(MultipartFile multipartFile) {
    // 1 参数校验
    if (multipartFile == null || multipartFile.getSize() == 0) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
    }
    // 得到userId
    WmUser user = WmThreadLocalUtils.getUser();
    if (user == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
    }
    // 上传到oss
    // 文件名
    String fileUrl = null;
    try {
      String fileName = UUID.randomUUID().toString().replace("-", "");
      String originalFilename = multipartFile.getOriginalFilename();
      String sufix = originalFilename.substring(originalFilename.lastIndexOf("."));
      fileUrl = fileStorageService.store(prefix, fileName + prefix, multipartFile.getInputStream());
      //            log.info("fileId: {}",fileUil);

      // 创建素材表信息,将图片路径存入
      // 封装数据
      WmMaterial wmMaterial = new WmMaterial();
      wmMaterial.setUserId(user.getId());
      wmMaterial.setUrl(fileUrl); // 设置oss中文件路径
      wmMaterial.setType((short) 0);
      wmMaterial.setIsCollection((short) 0);
      wmMaterial.setCreatedTime(new Date());

      // 素材保存到数据库
      this.save(wmMaterial);
      // 和前缀路径拼到一块
      wmMaterial.setUrl(webSite + fileUrl);
      return ResponseResult.okResult(wmMaterial);
    } catch (IOException e) {
      e.printStackTrace();
      log.error("文件上传出现异常==>> {}", e);
      return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "文件上传失败");
    }
  }

  @Override
  public ResponseResult finLlist(WmMaterialDto dto) {
    // 1.校验参数
    dto.checkParam();

    // 5.获取当前登录用户
    WmUser user = WmThreadLocalUtils.getUser();
    if (user == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
    }
    // 2.封装查询条件
    LambdaQueryWrapper<WmMaterial> lambdaQuery = Wrappers.<WmMaterial>lambdaQuery();
    // 3.分页条件
    IPage<WmMaterial> wmMaterialPage = new Page<>(dto.getPage(), dto.getSize());

    // 4.是否收藏
    if (dto.getIsCollection()==1){
      lambdaQuery.eq(WmMaterial::getIsCollection,1);
    }
    // 6.发布时间降序
    lambdaQuery.orderByDesc(WmMaterial::getCreatedTime);
    // 7.执行查询
    IPage<WmMaterial> resultPage = page(wmMaterialPage, lambdaQuery);

    // 处理图片
    List<WmMaterial> wmMaterials = resultPage.getRecords();
    //就是把图片地址补全之后返回即可
    for (WmMaterial wmMaterial : wmMaterials) {
      wmMaterial.setUrl(webSite + wmMaterial.getUrl());
    }
    // 8.分装结果返回
    ResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(),resultPage.getTotal());

    pageResponseResult.setData(wmMaterials);
    return pageResponseResult;
  }
  @Autowired
  WmNewsMaterialMapper wmNewsMaterialMapper;

  /**
   * 删除图片
   * @param id
   * @return
   */
  @Transactional
  @Override
  public ResponseResult delPicture(Integer id) {
    //1.查询id
    if (id==null){
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
    }
    //判断是否登录
    WmUser user = WmThreadLocalUtils.getUser();
    if(user==null){
      return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
    }
    //查询素材数据
    WmMaterial material = getById(id);
    if(material==null){
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
    if (!material.getUserId().equals(user.getId())){
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"无权限操作");
    }
    //3.查看素材是否引用,就是看看计次大于0么
    LambdaQueryWrapper<WmNewsMaterial> lambdaQuery = Wrappers.<WmNewsMaterial>lambdaQuery();
    lambdaQuery.eq(WmNewsMaterial::getMaterialId,id);

    Integer refCount = wmNewsMaterialMapper.selectCount(lambdaQuery);

    if (refCount>0){
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"素材被引用无法删除");
    }
    //删除素材
    removeById(id);
    //删除oss中的文件
    fileStorageService.delete(material.getUrl());

    return ResponseResult.okResult();
  }

  //收藏
  @Override
  public ResponseResult updateStatus(Integer id, Short status) {
    //1.查询id
    if (id==null){
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
    }
    //判断是否登录
    WmUser user = WmThreadLocalUtils.getUser();
    if(user==null){
      return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
    }
    LambdaUpdateWrapper<WmMaterial> lambdaUpdate = Wrappers.<WmMaterial>lambdaUpdate();
    lambdaUpdate.set(WmMaterial::getIsCollection,status)
            .eq(WmMaterial::getUserId,user.getId())
            .eq(WmMaterial::getId,id);
    update(lambdaUpdate);

    return ResponseResult.okResult();
  }
}
